require 'yaml'
require 'sanitize'
require 'json'
require 'awesome_print'

module TdBerlinTest
  class StackexchangeApiFetcher
    DefaultQueryURI = "https://api.stackexchange.com/2.2/tags"

    attr_accessor :language_data, :result

    def initialize(yaml_file)
      @language_data = parse_yaml_file(yaml_file)
    end

    def parse_yaml_file(yaml_file)
      YAML.load_file(yaml_file)
    end

    def run
      result_hash = {}
      @language_data[0]['langs'].each do |language|
        json = fetch_stackoverflow(language)
        tag_usage_count = get_tag_usage_count_from_json(json, language)
        result_hash[language] = tag_usage_count
      end

      @result = sort_result_by_tag_usage_count(result_hash)
      output_result(@result)
    end

    def fetch_stackoverflow(language)
      url = DefaultQueryURI + "?order=desc&sort=popular&inname=#{language}&site=stackoverflow"
      open(url).read
    end

    def get_tag_usage_count_from_json(json, language)
      parsed = JSON.parse(json)

      parsed['items'].each do |tag|
        if tag['name'] == language
          return tag['count']
        end
      end
    end

    def sort_result_by_tag_usage_count(hash)
      temp = hash.sort_by { |language, tag_usage_count| tag_usage_count }.reverse.to_h
    end

    def output_result(hash)
      ap @result, :indent => -2
    end
  end
end